package com.example.sicnuaccountingapp.ui.home

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.sicnuaccountingapp.data.entity.Transaction
import com.example.sicnuaccountingapp.databinding.ItemTransactionGroupBinding
import com.example.sicnuaccountingapp.databinding.ItemTransactionBinding

class GroupedTransactionAdapter(
    private val onItemClick: (Transaction) -> Unit
) : ListAdapter<Pair<String, List<Transaction>>, GroupedTransactionAdapter.GroupViewHolder>(GroupDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GroupViewHolder {
        val binding = ItemTransactionGroupBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return GroupViewHolder(binding)
    }

    override fun onBindViewHolder(holder: GroupViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class GroupViewHolder(
        private val binding: ItemTransactionGroupBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        private val transactionAdapter = TransactionAdapter(onItemClick)

        init {
            binding.transactionList.adapter = transactionAdapter
        }

        fun bind(group: Pair<String, List<Transaction>>) {
            binding.dateText.text = group.first
            transactionAdapter.submitList(group.second)
        }
    }

    private class GroupDiffCallback : DiffUtil.ItemCallback<Pair<String, List<Transaction>>>() {
        override fun areItemsTheSame(
            oldItem: Pair<String, List<Transaction>>,
            newItem: Pair<String, List<Transaction>>
        ): Boolean {
            return oldItem.first == newItem.first
        }

        override fun areContentsTheSame(
            oldItem: Pair<String, List<Transaction>>,
            newItem: Pair<String, List<Transaction>>
        ): Boolean {
            return oldItem == newItem
        }
    }
} 